package com.company.JUC;

import java.util.HashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo {
    public static void main(String[] args) {
        ReadWriteLockTest readWriteLockTest = new ReadWriteLockTest();
        for (int i = 0; i < 10; i++) {
            final int temp = i;
            new Thread(()->{
                readWriteLockTest.put(temp+" ",temp+"");
            },String.valueOf(i)).start();
        }
        for (int i = 0; i < 10; i++) {
            final int temp = i;
            new Thread(()->{
                readWriteLockTest.get(temp+" ");
            },String.valueOf(i)).start();
        }
    }

}
class ReadWriteLockTest{
    private HashMap<String,String> map = new HashMap<>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public void put(String key,String val){

        readWriteLock.writeLock().lock();
        System.out.println("写入"+key);
        map.put(key,val);
        System.out.println("写入"+key+"成功");
        readWriteLock.writeLock().unlock();
    }
    public void get(String key){
        readWriteLock.readLock().lock();
        map.get(key);
        System.out.println("读取成功"+key);
        readWriteLock.readLock().unlock();
    }
}
